package ProxyClient;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpDownloader implements IHttpDownloader {
	private static final int BUFFER_SIZE = 128 * 1024;
	private static final String[] supportedMediaFormats = new String[]{
		"jpg", "png", "gif"
	};
	
	public HttpDownloader(){}
	
	public HttpResource getResource(String urlAddress) {
    	String contents = "";
    	HttpResource ret = null;
		try {
			URL url = new URL(urlAddress);
			URLConnection connection = url.openConnection();
			InputStream in = new BufferedInputStream(url.openStream());
			String inputLine;	
	    	ByteArrayOutputStream out = new ByteArrayOutputStream();
	    	byte[] buf = new byte[BUFFER_SIZE];
	    	int n = 0;
	    	while (-1!=(n=in.read(buf))) {
	    	   out.write(buf, 0, n);
	    	}
	    	out.close();
	    	in.close();
	    	byte[] binaryData = out.toByteArray();
	    	ret = new HttpResource(urlAddress, binaryData);
	    	if (!isSupportedMediaFormat(urlAddress)) {
	    		ret.setContents(out.toString());
	    		ret.setIsMedia(false);
	    	}
	    	else {
	    		ret.setIsMedia(true);
	    	}
		} catch (MalformedURLException exc) {
			System.out.println("Invalid url provided");
			exc.printStackTrace();
		} catch (IOException exc) {
			System.out.println("An IO exception catched");
			exc.printStackTrace();
		}
		return ret;
	}
	
	public static boolean isSupportedMediaFormat(String path) {
		/** Get the extension **/
		int dotIndex = path.lastIndexOf('.');
		if(dotIndex>0) {
			String ext = path.substring(dotIndex+1);
			for(String format: supportedMediaFormats) {
				if(ext.equals(format)) {
					return true;
				}
			}
		}
		return false;
	} 
	
	public static void clearCache(){
		
	}

}
